<?php

  define('BASE_ROOT_PATH', dirname(dirname(__FILE__)));
	include_once( BASE_ROOT_PATH . "/word/db/DBMySQL.php");  

	$avaterType = $_REQUEST['type'];
	$memberId = $_REQUEST['id'];
	if(empty($memberId)) {
	  $msg = json_encode("用户id不能为空");
		echo '{"code":"1","msg":'.$msg.'}';
		exit();
	}
	
	// 查找用户
	$db = new DBMySQL();
	$rs = $db->Query("select mi.member_id,m.email from t_member m join t_member_info mi on mi.member_id = m.member_id where m.member_id = $memberId limit 1");
	if(empty($rs)) {
	  $msg = json_encode("该用户不存在");
		echo '{"code":"1","msg":'.$msg.'}';
		exit();
	}	

	// 对上传文件的处理	
	$fileName = $_FILES["userfile"]["name"];
  if(!empty($fileName)) {
    
    $tmpName = $_FILES["userfile"]["tmp_name"];
    
    $error = $_FILES["userfile"]["error"];
    if($error > 0) { // 上传失败
  	  $msg = json_encode("图片上传发生错误");
  		echo '{"code":"1","msg":'.$msg.'}';
      exit();
    }
    
    $fileSplit = explode(".", $fileName);    
    $nSize = count($fileSplit);
    if(2 > $nSize) { // 没有文件后缀名?
  	  $msg = json_encode("上传的文件'$fileName'不合法");
  		echo '{"code":"1","msg":'.$msg.'}';
      exit();
    }
    $suffix = $fileSplit[$nSize-1];

    $size = $_FILES["userfile"]["size"];
    if($size > 2097152) { // 超过2M
  	  $msg = json_encode("上传的图片超过2M");
  		echo '{"code":"1","msg":'.$msg.'}';
      exit();
    }
    
    $avater = $memberId."_".time().".".$suffix;
    move_uploaded_file($tmpName, "pic/$avater");

  	$val = $rs[0];
  	$memberId = $val['member_id'];
  	if (empty($avaterType) || $avaterType == "0") {
  		$db->Modify("update t_member_info mi set mi.avater='$avater' where mi.member_id = $memberId");
  	}
  	elseif ($avaterType == "1"){
  		$db->Modify("update t_member_info mi set mi.avater1='$avater' where mi.member_id = $memberId");
  	}
  	elseif ($avaterType == "2"){
  		$db->Modify("update t_member_info mi set mi.avater2='$avater' where mi.member_id = $memberId");
  	}
  	echo '{"code":"0","msg":"'.$avater.'"}';
  } else {
 	  $msg = json_encode("无图片上传");
 		echo '{"code":"1","msg":'.$msg.'}';    
  }
	
?>